from contextlib import asynccontextmanager

import os
import uvicorn
from fastapi import FastAPI

from database.database import engine
from models import Base
from scheduler import start_scheduler, stop_scheduler
from task import video_requests
from views.task_site_view import router as task_site_router
from views.task_video_view import router as task_video_router
from views.task_view import router as task_router
from views.video_view import router as video_router

# 创建数据库表
Base.metadata.create_all(bind=engine)

@asynccontextmanager
async def lifespan(app: FastAPI):    # 定义一个上下文管理器，用于启动和关闭时执行一些操作
    # 测试数据
    # video_requests.get_new_video_list()
    # video_requests.get_all_video_list()
    # 启动定时任务调度器
    start_scheduler(app)
    print("定时任务启动")
    yield
    # 关闭定时任务调度器
    stop_scheduler(app)
    print("定时任务 Shutting down")

app = FastAPI(
    title="Video API",
    description="Video management API",
    version="1.0.0",
    lifespan=lifespan,
    docs_url="/docs",
    redoc_url="/redoc"
)

# 添加路由
app.include_router(task_router)
app.include_router(task_site_router)
app.include_router(task_video_router)
app.include_router(video_router)



if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=False)